/**
 * 
 */
package demo.servlet.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.StrBuilder;

/**
 * @author roger.xu
 * 
 */
public class ServletUtilities {

    /**
     * Return a loop-back URL to the web application context. No trailing slash.
     * 
     * @param servletRequest
     *            The servlet request.
     * @return The context URL.
     */
    public static String getContextURL(HttpServletRequest servletRequest) {
        // build the URL from each defined piece
        final StrBuilder result = new StrBuilder();
        final String scheme = servletRequest.getScheme();
        final String host = servletRequest.getServerName();
        final int port = servletRequest.getServerPort();
        final String context = servletRequest.getContextPath();

        result.append(scheme).append("://").append(host); //$NON-NLS-1$

        // omit the port if it's a common default, for neatness
        if ((StringUtils.equalsIgnoreCase(scheme, "http") && (port != 80)) || (StringUtils.equalsIgnoreCase(scheme, "https") && (port != 443))) { //$NON-NLS-1$ //$NON-NLS-2$
            result.append(':').append(port);
        }

        result.append(context);

        return result.toString();
    }

}
